/**
 Created by:
 muhtearjan mehmood مۇختەرجان مەخمۇت (Email: yeganaaa@163.com)
 At 2/26/20 11:31 PM
 */
import {IRpcSocketServer, RpcBridgeHost} from "rpc_dream";

export class RpcSocketServerGroup implements IRpcSocketServer<void> {
    onClientConnected: (client: RpcBridgeHost<any>) => void = client => {}
    onError: (error: Error) => void = error => {}
    onLaunch: () => void = () => {}
    onShutDown: () => void = () => {}
    server: void = null!
    private serverInstances: IRpcSocketServer<any>[] = []
    constructor(private servers: (() => Promise<IRpcSocketServer<any>>)[]) {}

    public async prepareForLaunch(): Promise<void> {
        const waiters: Promise<void>[] = []
        let launchCount = 0
        let shutdownCount = 0
        for (const serverGenerator of this.servers) {
            const server = await serverGenerator()
            this.serverInstances.push(server)
            server.onClientConnected = client => this.onClientConnected(client)
            server.onError = error => this.onError(error)
            server.onLaunch = () => {
                shutdownCount++
                if (shutdownCount == this.serverInstances.length) {
                    this.onLaunch()
                    launchCount = 0
                }
            }
            server.onShutDown = () => {
                shutdownCount++
                if (shutdownCount == this.serverInstances.length) {
                    this.onShutDown()
                    shutdownCount = 0
                }
            }
            waiters.push(server.prepareForLaunch())
        }
        for (const wait of waiters) await wait
    }

    public async shutdown(): Promise<void> {
        const waiters: Promise<void>[] = []
        for (const server of this.serverInstances) waiters.push(server.shutdown())
        for (const wait of waiters) await wait
    }
}
